<?php

namespace app\api\controller;

use app\common\controller\Yangliu;
use EasyWeChat\Factory;
use think\Env;
use think\Session;

/**
 * 企业微信登录
 */
class WorkLogin extends Yangliu
{

    protected $noNeedLogin = ['login','test','index'];
    protected $noNeedRight = '*';

    public $Config;
    protected $keeptime = 2592000;

    public function _initialize()
    {
        parent::_initialize();
        $this->Config = [
            'agent_id' => Env::get('school.agent_id'),
            'corp_id' => Env::get('user.corp_id'),
            'secret'   => Env::get('school.secret'),
            'response_type' => Env::get('school.response_type'),
            'log' => [
                'level' => Env::get('school.level'),
                'file' => __DIR__.Env::get('school.file'),
            ],
            'oauth'=> [
                'scopes'=> Env::get('school.scopes'),
                'callback' => 'http://oa.fc62.com/api/work_login/index'
            ]
        ];
    }

    /**
     * @ApiTitle    (模拟登录)
     * @ApiSummary  (传userid 返回json 不传值用来开发测试)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/work_login/test/)
     * @ApiParams   (name="userid", type="string", required=true, description="用户的userid")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "Logged in successful",
    "time": "1574765625",
    "data": {
    "userinfo": {
    "id": 491,
    "username": "杨柳",
    "nickname": "0630349",
    "avatar": "http://wework.qpic.cn/wwhead/duc2TvpEgST9hicuyypLEKC2JppppE5DugzahDO8Tlmiav2anFMR5Xmk7ruooj9vvSwFe5bHpYEGU/0",
    "mobile": "17607118143",
    "token": "3675d389-44ba-4c29-866a-e856a65e956e",
    "user_id": 491,
    "createtime": 1574765625,
    "expiretime": 1577357625,
    "expires_in": 2592000
    }
    }
    })
     */
    public function test($ids = null)
    {
        $ret = $this->request->get('userid');
        if ($ret) {
            $this->auth->login($ret);
            $data = ['userinfo' => $this->auth->getUserinfo()];
            if($ids)
            {
                $this->auth->login($ids);
                $data = ['userinfo' => $this->auth->getUserinfo()];
                return redirect('http://oa.com/outer/#/?token='.$data['userinfo']['token']);
            }
            $this->success(__('Logged in successful'), $data);

        } else {
            $this->auth->login('admin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            return redirect('/outer/#/?token='.$data['userinfo']['token']);
        }
    }


    /**
     * @ApiTitle    (获取用户信息)
     * @ApiSummary  (getWorkInfo)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/work_login/getWorkInfo/)
     * @ApiParams   (name="token", type="string", required=true, description="token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "Logged in successful",
    "time": "1574765625",
    "data": {
    "userinfo": {
    "id": 491,
    "username": "杨柳",
    "nickname": "0630349",
    "avatar": "http://wework.qpic.cn/wwhead/duc2TvpEgST9hicuyypLEKC2JppppE5DugzahDO8Tlmiav2anFMR5Xmk7ruooj9vvSwFe5bHpYEGU/0",
    "mobile": "17607118143",
    "token": "3675d389-44ba-4c29-866a-e856a65e956e",
    "user_id": 491,
    "createtime": 1574765625,
    "expiretime": 1577357625,
    "expires_in": 2592000
    }
    }
    })
     * */
    public function getWorkInfo()
    {
        $data = ['userinfo' => $this->auth->getUserinfo()];
        $this->success(__('Logged in successful'), $data);
    }

    /**
     * @ApiTitle    (登录跳转vue页面)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/work_login/index/)
     * @ApiParams   (name="code", type="string", required=true, description="企业微信回调的参数")
     */
    public function index()
    {
        Session::set('login_url',$this->request->get('return_url'));
        if($code = $this->request->request('code'))
        {
            $app = Factory::work($this->Config);
            $token = $app->access_token->getToken();//获取企业微信token
            $code = $this->request->request('code');
            $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={$token['access_token']}&code={$code}";
            $user = \fast\Http::get($url);
            if(!empty($user)) $user = json_decode($user,true);
            $this->auth->login($user['UserId']);
        }
        if(!$this->auth->isLogin()){
            //跳转到登录
            $auth = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->Config['corp_id']."&redirect_uri=".$this->Config['oauth']['callback']."&response_type=code&scope=".$this->Config['oauth']['scopes']."&agentid=".$this->Config['agent_id']."&state=STATE#wechat_redirect";
            return redirect($auth);
        }
        $userinfo = $this->auth->getUserinfo();
        if(!$url = Session::get('login_url'))
        {
            $url = '/outer/#/?token='.$userinfo['token'];
        }
        return redirect($url);
    }

    /**
     * @ApiTitle    (企业微信授权)
     * @ApiSummary  (无法测试，用企业微信访问即可)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/work_login/login/)
     */
    public function login()
    {
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->Config['corp_id']."&redirect_uri=".$this->Config['oauth']['callback']."&response_type=code&scope=".$this->Config['oauth']['scopes']."&agentid=".$this->Config['agent_id']."&state=STATE#wechat_redirect";
        return redirect($url);
    }

    /**
     * @ApiTitle    (退出登录)
     * @ApiSummary  (退出登录)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/work_login/logout/)
     * @ApiParams   (name="token", type="string", required=true, description="token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

}
